// 
//  Copyright 2011  reda
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
using System;
using ManiacMusicManager.Data.Exceptions;
using NHibernate;

namespace ManiacMusicManager.Data
{
	public partial class SessionManager : IDisposable
	{
		#region Champs privés
		private ISession _currentSession;
		#endregion
		
		#region ISession
		/// <summary>
		/// Renvoie une réference vers une session Hibernate
		/// </summary>
		/// <returns>
		/// A <see cref="ISession"/>
		/// </returns>
		public ISession Session {
			get {
				if(! this.IsAccessible)
					throw new InvalidSessionException();
				
				try {
					this.Lock();
					var session = GetCurrentSession();
					if(session == null) {
						NewSession();
						session = GetCurrentSession();
					}
						
					return session;
				}
				catch(Exception e) {
					throw new SessionManagementException(e);
				}
				finally {
					this.Unlock();
				}
			}
		}
		
		/// <summary>
		/// Ouvre une nouvelle session, si il y a une déja ouverte elle est fermée
		/// </summary>
		private void NewSession() {
			try {
				this.Lock();
				CloseSession();
				this._currentSession = Factory.OpenSession();
			}
			catch(Exception e) {
				throw new SessionManagementException(e);
			}
			finally {
				this.Unlock();
			}
		}
		
		/// <summary>
		/// Ferme la session en cours
		/// </summary>
		private void CloseSession() {
			try {
				this.Lock();
				var session = GetCurrentSession();
				if(session!=null)
					session.Close();
			}
			catch(Exception e) {
				throw new SessionManagementException(e);
			}
			finally {
				this.Unlock();
			}
		}
		
		/// <summary>
		/// Retourne l'objet ISession valide en cours
		/// </summary>
		/// <returns>
		/// Session valide en cours ou null
		/// </returns>
		private ISession GetCurrentSession() {
			try {
				this.Lock();
				if((this._currentSession==null) || !this._currentSession.IsOpen)
					this._currentSession = null;
				
				return this._currentSession;
			}
			catch(Exception e) {
				throw new SessionManagementException(e);
			}
			finally {
				this.Unlock();
			}
		}
		#endregion
	}
}

